﻿using RemotingObject;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading.Tasks;

namespace EnvCommonUtility
{
    /// <summary>
    /// 客户端
    /// </summary>
    public class RemotingOperation4Client
    {
        #region 变量

        private RemotingObj obj;

        #endregion

        #region 构造函数

        public RemotingOperation4Client()
        {

        }

        #endregion

        #region 私有方法

        private void obj_SubscribeAtClient(string msg)
        {
#if DEBUG
            Debug.WriteLine("Server: " + msg);
            Console.WriteLine("Server: " + msg);
#endif
        }

        #endregion

        #region 公开的方法

        /// <summary>
        /// 开启客户端
        /// </summary>
        public void StartClient()
        {
            // 设置反序列化级别
            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
            serverProvider.TypeFilterLevel = TypeFilterLevel.Full; // 支持所有类型的反序列化，级别很高

            // 信道端口
            IDictionary idic = new Dictionary<string, int>();
            idic["port"] = 0;

            // 注册信道
            TcpChannel tcpchannel = new TcpChannel(idic, clientProvider, serverProvider);
            ChannelServices.RegisterChannel(tcpchannel, false);

            // 获取代理
            obj = (RemotingObj)Activator.GetObject(typeof(RemotingObj), "tcp://192.168.1.223:9438/url");
            // 订阅服务器事件
            Swap swap = new Swap();
            obj.SubscribeAtClient += new MyDelegate(swap.TriggerAtServerSwapEvent);
            swap.SwapSubscribeAtClient += new MyDelegate(obj_SubscribeAtClient);
        }

        // 获取本地 IP
        public string ClientIP()
        {
            return System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0].ToString();
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="infor">消息</param>
        public void SendInformation(string infor)
        {
            obj.TriggerAtClient("客户端--" + this.ClientIP() + System.Environment.NewLine + infor + System.Environment.NewLine);
        }

        #endregion
    }
}
